//万能表单
var WxParse = require('../../wxParse/wxParse.js');
var app = getApp()
Page({
  data: {

  },
  onLoad: function (e) {
    var that = this;
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    if(e&&e.id){
      that.setData({
        id:e.id
      })
    }
    app.setNavColor(that);

    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        that.requestFormdata();
      }
    } else {
      that.requestFormdata();
    }
  },
  // 请求表单数据
  requestFormdata: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_custom_form',
        id: that.data.id ? that.data.id:''
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data)
          var formData = res.data.data.formData;
          // 富文本解析
          if (formData) {
            for (var i = 0; i < formData.length; i++) {
              formData[i].id = i;
              formData[i].value = '';
              if (formData[i].type == 'intro') {
                var detail = formData[i].data.detail;
                var detailNodes = 'detail' + i;
                WxParse.wxParse(detailNodes, 'html', detail, that, 5);
                formData[i].nodes = that.data[detailNodes].nodes;
              }
            }
            that.setData({
              formTitle: res.data.data.title,
              formData: formData,
              formId: res.data.data.id
            })
            if (res.data.data.title) {
              wx.setNavigationBarTitle({
                title: res.data.data.title
              })
            }
          }
          console.log(that.data);
        } else {
          console.log(res.data)
          wx.setNavigationBarTitle({
            title: '自定义表单'
          })
          that.setData({
            formData: []
          })
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  onPullDownRefresh: function () {
    var that = this;
    that.onLoad();
  },
  backsy: function () {
    app.backHome();
  },
  // 监控数据改变
  dataChange: function (e) {
    var that = this;
    var formData = that.data.formData;
    var id = e.currentTarget.dataset.id;
    var curVal = e.detail.value;
    console.log(e);
    for (var i = 0; i < formData.length; i++) {
      if (formData[i].id == id) {
        if (formData[i].type == 'select') {
          that.setData({
            [`formData[${i}].value`]: formData[i].data.options[curVal].title
          })
        } else {
          that.setData({
            [`formData[${i}].value`]: curVal
          })
        }
        
      }
    }
  },
  chooseLocation: function (e) {
    var that = this;
    var formData = that.data.formData;
    var id = e.currentTarget.dataset.id;
    wx.chooseLocation({
      success: (res) => {
        console.log(res);
        var value = [];
        value.push(res.address);
        value.push(res.latitude);
        value.push(res.longitude);
        for (var i = 0; i < formData.length; i++) {
          if (formData[i].id == id) {
            formData[i].value = value;
            formData[i].valueShow = res.address;
          }
        }
        console.log(formData);
        console.log(id);
        that.setData({
          formData: formData
        })
        console.log(that.data.formData);
      },
      fail: function () {
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.userLocation']) {
              that.setData({
                isShowsetting: true
              })
            }else{
              that.setData({
                locationTips: "无法获取您的当前定位地址，请打开定位权限"
              })
            }
          }
        })
      }
    })
  },
  hideSetting: function() {
    var that = this;
    that.setData({
      isShowsetting: false
    })
  },
  openSetting: function() {
    var that = this;
    that.hideSetting();
    wx.openSetting({
      success: (res) => {
        res.authSetting = {
          "scope.userLocation": true
        }
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  // 上传图片
  chooseSingleImage: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#333",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', id)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', id)
          }
        }
      }
    })
  },
  //选择单图
  chooseWxImage: function (type, id) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        console.log(res);
        var temPath = res.tempFilePaths[0];
        that.upload_file(temPath, id);
      }
    })
  },
  // 上传单图到服务器
  upload_file: function (temPath, id) {
    var that = this;
    var formData = that.data.formData;
    wx.showLoading({
      title: '上传中',
    })
    wx.uploadFile({
      url: app.globalData.requestUrl + '?&map=applet_img_upload',
      filePath: temPath,
      name: 'image',
      success: function (res) {
        var data = JSON.parse(res.data);
        var realpath = app.globalData.domin + data.data.path;
        if (data.ec == 200) {
          for (var i = 0; i < formData.length; i++) {
            if (formData[i].id == id) {
              formData[i].img = realpath;
              formData[i].value = data.data.path;
            }
          }
          that.setData({
            formData: formData
          })
          console.log(that.data.formData);
        } else {
          wx.showModal({
            title: '提示',
            content: data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  submitData: function () {
    var that = this;
    app.getSubId(that, 'applet_submit_form_data', 'toSubmitData');
  },
  toSubmitData: function () {
    var that = this;
    var formData = that.data.formData;
    for (var i = 0; i < formData.length; i++) {
      if (formData[i].require == 'true') {
        if (formData[i].value == '') {
          app.errorTip(that, formData[i].data.title + '为必填项', 2000);
          return;
        }
      }
      if (formData[i].type == 'intro') {
        formData[i].data.detail = '';
        formData[i].nodes = '';
      }
    }
    var data = {
      map: 'applet_submit_form_data',
      data: JSON.stringify(formData),
      id: that.data.formId ? that.data.formId:''
    }
    console.log(data);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data)
          for (var i = 0; i < formData.length; i++) {
            if (formData[i].type == 'upload') {
              formData[i].img = '';
            }
            formData[i].value = '';
            formData[i].valueShow = '';
          }
          that.setData({
            formData: formData
          })
          app.errorTip(that, res.data.data.msg, 2000);
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  onShareAppMessage: function () {
    var that = this;
    var id = that.data.id;
    var formTitle = that.data.formTitle ? that.data.formTitle:'';
    var shareInfo = app.globalData.shareInfo ? app.globalData.shareInfo:'';
    var title = shareInfo.shareTitle ? shareInfo.shareTitle : formTitle;
    var cover = shareInfo.shareCover ? shareInfo.shareCover : '';
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: '/pages/generalForm/generalForm?id=' + id
    }
  }
})
